package cn.k.interceptor;

import cn.k.domain.Employee;
import cn.k.service.IPermissionService;
import cn.k.util.RequirePermission;
import cn.k.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拿到session
        Employee employee = UserContext.getEmployee();
        if (employee.isAdmin()) {//是管理员
            return true;
        } else {//不是管理员
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RequirePermission annotation = handlerMethod.getMethodAnnotation(RequirePermission.class);
            if (annotation == null) {
                return true;
            }
            //这个方法需要权限控制
            //获取当前访问方法权限表达式
            //为什么用expression而不用id？因为id会自增长，而expression不会变
            String expression = annotation.expression();


            //查询当前访问员工权限 从session中取，也就是从内存中取，不发送sql，提高性能
            //List<String> expressions= permissionService.queryExpressionByEmployeeId(employee.getId());
           // List<String> expressions = (List<String>) request.getSession().getAttribute("EXPRESSIONS_IN_SESSION");
            List<String> expressions = UserContext.getExpression();
            if (expressions.contains(expression)) {
                return true;
            }
            //不是管理员，方法需要权限控制，但此员工没有权限
//        注：这个是针对jsp freeMaker不支持直接跳转
//        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request, response);
//        需要用controller
            response.sendRedirect("/nopermission");
            return false;
        }
    }
}
